package com.test.captcha.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.test.captcha.model.CaptchaYml;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaYml captchaYml;

    private final static Long VALID_TIME = 30 * 60 * 1000L;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response){
        long start = System.currentTimeMillis();
        response.setContentType("image/jpeg");
        try {
            //定义图形验证码的长和宽
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
            String code = lineCaptcha.getCode();
            session.setAttribute(captchaYml.getSession().getKey(),code);
            session.setAttribute(captchaYml.getSession().getDate(),new Date());
            lineCaptcha.write(response.getOutputStream());
            System.out.println(code);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
//        System.out.println("生成验证码到返回验证码所用的时间为：" + (end-start) + "ms");

    }

    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session){
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        String code = (String) session.getAttribute(captchaYml.getSession().getKey());
        Date date = (Date) session.getAttribute(captchaYml.getSession().getDate());
        //String.equals验证字符串是否相同有区分大小写，而equalsIgnoreCase没有
        if (code.equalsIgnoreCase(captcha) && date != null && (System.currentTimeMillis()-date.getTime()) < VALID_TIME){
            return true;
        }
        return false;
    }
}
